package 链表题目;

import 链表题目.model.ListNode;

//旋转链表
//https://leetcode.cn/problems/rotate-list/
//给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
class 旋转链表 {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) return head;
        ListNode dummy = new ListNode(0, head);
        int nodeSum = 1;
        // 一轮遍历之后head变成尾节点
        while (head.next != null) {
            head = head.next;
            nodeSum++;
        }
        //变成环链表
        head.next = dummy.next;
        int needMove = nodeSum - k % nodeSum;
        while (needMove > 0) {
            head = head.next;
            needMove--;
        }
        ListNode ans = head.next;
        head.next = null;
        return ans;
    }

    public static void main(String[] args) {
        旋转链表 solution = new 旋转链表();
        ListNode one6 = new ListNode(6, null);
        ListNode one5 = new ListNode(5, one6);
        ListNode one4 = new ListNode(4, one5);
        ListNode one3 = new ListNode(3, one4);
        ListNode one2 = new ListNode(2, one3);
        ListNode one1 = new ListNode(1, one2);
        solution.rotateRight(one1, 3);
    }
}
